package com.irdstudio.rsp.rule.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.irdstudio.rsp.rule.common.BizUtil;
import com.irdstudio.rsp.rule.common.constant.Constant.ADAPTER_TYPE;
import com.irdstudio.rsp.rule.common.constant.Constant.RULE_COLL_TYPE;
import com.irdstudio.rsp.rule.dao.SRuleCollInfoDao;
import com.irdstudio.rsp.rule.dao.SRuleParamDao;
import com.irdstudio.rsp.rule.dao.domain.SRuleCollInfo;
import com.irdstudio.rsp.rule.dao.domain.SRuleParam;
import com.irdstudio.rsp.rule.service.vo.SRuleCollDetailVO;
import com.irdstudio.rsp.rule.service.vo.SRuleInfoWithParamVO;
import com.irdstudio.rsp.rule.service.vo.SRuleParamVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.irdstudio.rsp.rule.service.facade.SRuleInfoService;
import com.irdstudio.rsp.rule.dao.SRuleInfoDao;
import com.irdstudio.rsp.rule.dao.domain.SRuleInfo;
import com.irdstudio.rsp.rule.service.vo.SRuleInfoVO;
import com.irdstudio.sdk.beans.core.base.FrameworkService;
/**
 * <p>ServiceImpl: 规则信息表				<p>
 * @author AutoCoder
 * @date 2019-10-30
 */
@Service("sRuleInfoServiceImpl")
public class SRuleInfoServiceImpl implements SRuleInfoService, FrameworkService {
	
	private static Logger logger = LoggerFactory.getLogger(SRuleInfoServiceImpl.class);

	@Autowired
	private SRuleInfoDao sRuleInfoDao;

	@Autowired
	private SRuleParamDao sRuleParamDao;

	@Autowired
	private SRuleCollInfoDao sRuleCollInfoDao;
	
	/**
	 * 新增操作
	 */
	public int insertSRuleInfo(SRuleInfoVO inSRuleInfoVo) {
		logger.debug("当前新增数据为:"+ inSRuleInfoVo.toString());
		int num = 0;
		try {
			SRuleInfo sRuleInfo = new SRuleInfo();
			beanCopy(inSRuleInfoVo, sRuleInfo);
			num = sRuleInfoDao.insertSRuleInfo(sRuleInfo);
		} catch (Exception e) {
			logger.error("新增数据发生异常!", e);
			num = -1;
			throw e;
		}
		logger.debug("当前新增数据条数为:"+ num);
		return num;
	}

	/**
	 * 删除操作
	 */
	public int deleteByPk(SRuleInfoVO inSRuleInfoVo) {
		logger.debug("当前删除数据条件为:"+ inSRuleInfoVo);
		int num = 0;
		try {
			SRuleInfo sRuleInfo = new SRuleInfo();
			beanCopy(inSRuleInfoVo, sRuleInfo);
			num = sRuleInfoDao.deleteByPk(sRuleInfo);
		} catch (Exception e) {
			logger.error("删除数据发生异常!", e);
			num = -1;
			throw e;
		}
		logger.debug("根据条件:"+ inSRuleInfoVo +"删除的数据条数为"+ num);
		return num;
	}


	/**
	 * 更新操作
	 */
	public int updateByPk(SRuleInfoVO inSRuleInfoVo) {
		logger.debug("当前修改数据为:"+ inSRuleInfoVo.toString());
		int num = 0;
		try {
			SRuleInfo sRuleInfo = new SRuleInfo();
			beanCopy(inSRuleInfoVo, sRuleInfo);
			num = sRuleInfoDao.updateByPk(sRuleInfo);
		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
			throw e;
		}
		logger.debug("根据条件:"+ inSRuleInfoVo +"修改的数据条数为"+ num);
		return num;
	}
	
	/**
	 * 查询操作
	 */
	public SRuleInfoVO queryByPk(SRuleInfoVO inSRuleInfoVo) {
		
		logger.debug("当前查询参数信息为:"+ inSRuleInfoVo);
		try {
			SRuleInfo querySRuleInfo = new SRuleInfo();
			beanCopy(inSRuleInfoVo, querySRuleInfo);
			SRuleInfo queryRslSRuleInfo = sRuleInfoDao.queryByPk(querySRuleInfo);
			if (Objects.nonNull(queryRslSRuleInfo)) {
				SRuleInfoVO outSRuleInfoVo = beanCopy(queryRslSRuleInfo, new SRuleInfoVO());
				logger.debug("当前查询结果为:"+ outSRuleInfoVo.toString());
				return outSRuleInfoVo;
			} else {
				logger.debug("当前查询结果为空!");
			}
		} catch (Exception e) {
			logger.error("查询数据发生异常!", e);
		}
		return null;
	}


	/**
	 * 查询用户权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<SRuleInfoVO> queryAllOwner(SRuleInfoVO sRuleInfoVo) {

		logger.debug("当前查询本人所属数据信息的参数信息为:");
		List<SRuleInfoVO> list = null;
		try {
		    if (StringUtils.isNotBlank(sRuleInfoVo.getSort())) {
		        String sort = BizUtil.transferCamelCaseToHyphen(sRuleInfoVo.getSort());
		        sRuleInfoVo.setSort(sort);
            }
            if (StringUtils.isBlank(sRuleInfoVo.getOrder())) {
		        sRuleInfoVo.setOrder("asc");
            }
			List<SRuleInfo> sRuleInfos = sRuleInfoDao.queryAllOwnerByPage(sRuleInfoVo);
			logger.debug("当前查询本人所属数据信息的结果集数量为:"+ sRuleInfos.size());
			pageSet(sRuleInfos, sRuleInfoVo);
			list = (List<SRuleInfoVO>) beansCopy(sRuleInfos, SRuleInfoVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}

	@Override
	public List<SRuleInfoVO> queryAllExcludeRuleColl(SRuleCollDetailVO sRuleInfoVo) {
		logger.debug("当前查询排除规则集已关联规则的参数信息为:");
		List<SRuleInfoVO> list = null;
		try {
            if (StringUtils.isNotBlank(sRuleInfoVo.getSort())) {
                String sort = BizUtil.transferCamelCaseToHyphen(sRuleInfoVo.getSort());
                sRuleInfoVo.setSort(sort);
            }
            if (StringUtils.isBlank(sRuleInfoVo.getOrder())) {
                sRuleInfoVo.setOrder("asc");
            }
			SRuleCollInfo collInfo = sRuleCollInfoDao.queryByRuleCollId(sRuleInfoVo.getRuleCollId());
            if (collInfo != null && collInfo.getRuleCollType() != null) {
            	// 回写规则适用过滤条件
				sRuleInfoVo.setAdapterTypes(new ArrayList<>(5));
				if (collInfo.getRuleCollType().equals(RULE_COLL_TYPE.Approval.getCode())) {
					// 审批大纲
					sRuleInfoVo.getAdapterTypes().add(ADAPTER_TYPE.Approval.getCode());
				} else if (collInfo.getRuleCollType().equals(RULE_COLL_TYPE.SpecialApproval.getCode())) {
					// 特批审批大纲
					sRuleInfoVo.getAdapterTypes().add(ADAPTER_TYPE.SpecialApproval.getCode());
				} else {
					// 资方
					sRuleInfoVo.getAdapterTypes().add(ADAPTER_TYPE.Management.getCode());
				}
				sRuleInfoVo.getAdapterTypes().add(ADAPTER_TYPE.ALL.getCode());
			}
			List<SRuleInfo> sRuleInfos = sRuleInfoDao.queryAllExcludeRuleCollByPage(sRuleInfoVo);
			logger.debug("当前查询排除规则集已关联规则的结果集数量为:"+ sRuleInfos.size());
			pageSet(sRuleInfos, sRuleInfoVo);
			list = (List<SRuleInfoVO>) beansCopy(sRuleInfos, SRuleInfoVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}

		return list;
	}


	/**
	 * 查询当前机构权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<SRuleInfoVO> queryAllCurrOrg(SRuleInfoVO sRuleInfoVo) {

		logger.debug("当前查询本人所属机构数据信息的参数信息为:");
		List<SRuleInfo> sRuleInfos = sRuleInfoDao.queryAllCurrOrgByPage(sRuleInfoVo);
		logger.debug("当前查询本人所属机构数据信息的结果集数量为:"+sRuleInfos.size());
		List<SRuleInfoVO> list = null;
		try {
			pageSet(sRuleInfos, sRuleInfoVo);
			list = (List<SRuleInfoVO>) beansCopy(sRuleInfos, SRuleInfoVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}


	/**
	 * 查询当前机构及下属机构权限数据
	 */
	@SuppressWarnings("unchecked")
	public List<SRuleInfoVO> queryAllCurrDownOrg(SRuleInfoVO sRuleInfoVo) {

		logger.debug("当前查询本人所属机构及以下数据信息的参数信息为:");
		List<SRuleInfo> sRuleInfos = sRuleInfoDao.queryAllCurrDownOrgByPage(sRuleInfoVo);
		logger.debug("当前查询本人所属机构及以下数据信息的结果集数量为:"+ sRuleInfos.size());
		List<SRuleInfoVO> list = null;
		try {
			pageSet(sRuleInfos, sRuleInfoVo);
			list = (List<SRuleInfoVO>) beansCopy(sRuleInfos, SRuleInfoVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}

	/**
	 * 检查规则与参数信息
	 * @param infoWithParamVO
	 * @return
	 */
	public SRuleInfoWithParamVO queryRuleInfoWithParam(SRuleInfoWithParamVO infoWithParamVO) {

		String ruleId = infoWithParamVO.getRuleId(); //规则id
		SRuleInfoVO sRuleInfoVO = new SRuleInfoVO();
		sRuleInfoVO.setRuleId(ruleId);
		sRuleInfoVO = this.queryByPk(sRuleInfoVO);

		SRuleInfoWithParamVO result = new SRuleInfoWithParamVO();

		SRuleParamVO condi = new SRuleParamVO();
		condi.setRuleId(ruleId);
		List<SRuleParam> params = sRuleParamDao.queryAllOwner(condi);
		try {
			beanCopy(sRuleInfoVO, result);
			List<SRuleParamVO> list = (List<SRuleParamVO>) beansCopy(params, SRuleParamVO.class);
			result.setParams(list);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		return result;
	}

	/**
	 * 新增更新规则与参数信息
	 * @param infoWithParamVO
	 * @return
	 */
	public int updateRuleInfoWithParam(SRuleInfoWithParamVO infoWithParamVO){

		String ruleId = infoWithParamVO.getRuleId();
		String userId = infoWithParamVO.getUpdateUser();
		String updateTime = infoWithParamVO.getUpdateTime();
		if (StringUtils.isBlank(ruleId)) {
			throw new RuntimeException("规则Id为空");
		}

		SRuleInfo info = new SRuleInfo();
		info.setRuleId(ruleId);
		info = sRuleInfoDao.queryByPk(info);
		int num = 0;
		if (info == null) {
			// 新增
			info = new SRuleInfo();
			beanCopy(infoWithParamVO, info);
			info.setUpdateTime(updateTime);
			info.setUpdateUser(userId);
			info.setCreateUser(userId);
			info.setCreateTime(updateTime);
			num = sRuleInfoDao.insertSRuleInfo(info);
			// 处理参数
			if (CollectionUtils.isNotEmpty(infoWithParamVO.getParams())) {
				saveRuleParam(infoWithParamVO, ruleId, userId, updateTime);
			}
		} else {
			// 更新
			beanCopy(infoWithParamVO, info);
			info.setUpdateTime(updateTime);
			info.setUpdateUser(userId);
			num = sRuleInfoDao.updateByPk(info);
			// 处理参数
			if (CollectionUtils.isNotEmpty(infoWithParamVO.getParams())) {
				saveRuleParam(infoWithParamVO, ruleId, userId, updateTime);
			}
		}
		return num;
	}

	/**
	 * 保存规则参数
	 * @param infoWithParamVO
	 * @param ruleId
	 * @param userId
	 * @param updateTime
	 */
	private void saveRuleParam(SRuleInfoWithParamVO infoWithParamVO, String ruleId, String userId, String updateTime) {
		sRuleParamDao.deleteByRuleId(ruleId);
		List<SRuleParamVO> params = infoWithParamVO.getParams();
		for (SRuleParamVO paramVO : params) {
            paramVO.setRuleId(ruleId);
            SRuleParam param = new SRuleParam();
            beanCopy(paramVO, param);
            param.setUpdateTime(updateTime);
            param.setUpdateUser(userId);
            param.setCreateUser(userId);
            param.setCreateTime(updateTime);
            sRuleParamDao.insertSRuleParam(param);
        }
	}

	/**
	 * 删除规则与参数信息
	 * @param infoWithParamVO
	 * @return
	 */
	public int deleteRuleInfoWithParam(SRuleInfoWithParamVO infoWithParamVO){
		String ruleId = infoWithParamVO.getRuleId();
		if (StringUtils.isBlank(ruleId)) {
			throw new RuntimeException("规则Id为空");
		}
		SRuleInfo info = new SRuleInfo();
		info.setRuleId(ruleId);
		info.setCreateUser(infoWithParamVO.getCreateUser());
		int num = sRuleInfoDao.deleteByPk(info);
		sRuleParamDao.deleteByRuleId(ruleId);
		return num;
	}
}
